package org.windey.client;

import java.awt.AWTException;
import java.awt.Image;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.Toolkit;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.net.InetAddress;
import java.net.UnknownHostException;

import javax.swing.JOptionPane;

import org.windey.WindeyProtocol;
/**
 * 
 * de gebruikersinterface voor het client-programma
 *
 */
public class ClientGUI implements WindeyClientThreadInterface
{
	/**
	 * we maken een trayicon
	 */
	private TrayIcon trayIcon;
	/**
	 * trayicon heeft een logo
	 */
	private Image logoIcon;
	/**
	 * om connectie naar de server te leggen
	 */
	private WindeyServerConnection connection;
	/**
	 * de settings die lokaal zijn opgeslagen
	 */
	private WindeySettings settings;
	/**
	 * thread voor clientstream
	 */
	private WindeyClientStreamThread wcst;
	/**
	 * thread voor clientDataProvider
	 */
	private WindeyClientDataProvider wcdp;
	/**
	 * thread voor ClientReceive
	 */
	private WindeyClientReceiveThread wcrt;
	/**
	 * thread voor ClientDataHandler
	 */
	private WindeyClientDataHandler wcdh;
	/**
	 * bijhouden of er gestreamed wordt
	 */
	private boolean streaming;
	/**
	 * bijhouden of er gegevens worden ontvangen
	 */
	private boolean receiving;
	

	/**
	 * aanmaken van een clientgui
	 * @param settings de settings die zijn opgeslagen
	 */
	
	
	public ClientGUI(WindeySettings settings)
	{
		this.streaming = false;
		this.receiving = false;
		this.settings = settings;
		try
		{
			settings.loadSettings();
		}
		catch (SettingsException e)
		{
			settings.loadDefaultSettings();
			e.printStackTrace();
			showErrorMessage("Error loading settings");
		}
		connection = new WindeyServerConnection(this.settings);
	}
	
	/**
	 * maken van een Trayicon met benodigdheden
	 */
	public void show()
	{
		if (SystemTray.isSupported())
		{
		    SystemTray tray = SystemTray.getSystemTray();
		    try
		    {
		    	logoIcon = Toolkit.getDefaultToolkit().getImage(this.getClass().getResource("windey.gif"));
		    }
		    catch (Exception e)
		    {
		    	
		    }

		    MouseListener mouseListener = new MouseListener() {

				@Override
				public void mouseClicked(MouseEvent e) {
					
					// TODO Auto-generated method stub
					
				}

				@Override
				public void mouseEntered(MouseEvent e) {
					// TODO Auto-generated method stub
					
				}

				@Override
				public void mouseExited(MouseEvent e) {
					// TODO Auto-generated method stub
					
				}

				@Override
				public void mousePressed(MouseEvent e) {
					// TODO Auto-generated method stub
					
				}

				@Override
				public void mouseReleased(MouseEvent e) {
					// TODO Auto-generated method stub
					
				}
		                
		    };

		    ActionListener exitListener = new ActionListener() {
		        public void actionPerformed(ActionEvent e) {
		        	disconnect() ;
		            System.exit(0);
		        }
		    };
		            
		    PopupMenu menu = new PopupMenu();
		    MenuItem connect = new MenuItem("Connect") ;
		    MenuItem disconnect = new MenuItem("Disconnect") ;
		    MenuItem settings = new MenuItem("Settings");
		    MenuItem exit = new MenuItem("Exit");
		    
		    connect.addActionListener(new ActionListener() {

				public void actionPerformed(ActionEvent arg0) {
					connect() ;
					
				}
		    	
		    }) ;
		    
		    disconnect.addActionListener(new ActionListener() {

				public void actionPerformed(ActionEvent arg0) {
					disconnect() ;
					
				}
		    	
		    }) ;
		    
		    settings.addActionListener(new ActionListener(){

				public void actionPerformed(ActionEvent e)
				{
					showSettingsDialog();
				}


		    	
		    });
		    exit.addActionListener(exitListener);
		    menu.add(connect) ;
		    menu.add(disconnect) ;
		    menu.addSeparator();
		    menu.add(settings);
		    menu.addSeparator();
		    menu.add(exit);

		    trayIcon = new TrayIcon(logoIcon, "Windey's remote desktop control", menu);

		    ActionListener actionListener = new ActionListener() {
		        public void actionPerformed(ActionEvent e) {
		            trayIcon.displayMessage("Action Event", 
		                "An Action Event Has Been Performed!",
		                TrayIcon.MessageType.INFO);
		        }
		    };
		            
		    trayIcon.setImageAutoSize(true);
		    trayIcon.addActionListener(actionListener);
		    trayIcon.addMouseListener(mouseListener);

		    try {
		        tray.add(trayIcon);
		    } catch (AWTException e) {
		        System.err.println("TrayIcon could not be added.");
		    }

		} else {

		    //  System Tray is not supported
			System.err.println("System Tray is not supported. Instal a decent java version!!");

		}

	}
	
	private void showSettingsDialog()
	{
		new SettingsDialog(settings);
	}
	
	private void connect()  
	{
		try
		{
			connection.connect();
			//WindeyProtocol.authenticate(settings.getEmail(), settings.getPassword(), InetAddress.getLocalHost().getHostName(), connection);
			connection.send("testkey");
			wcdp = new WindeyClientDataProvider(this);
			wcst = new WindeyClientStreamThread(wcdp, this, connection);
			wcdh = new WindeyClientDataHandler(this);
			wcrt = new WindeyClientReceiveThread(wcdh, wcst, this, connection);
			wcrt.start();
			JOptionPane.showMessageDialog(null, "connectie geslaagd") ;
		}
		catch (WindeyServerConnectionException e)
		{
			e.printStackTrace();
			showErrorMessage("Unable to connect");
		}
		/*catch (UnknownHostException e)
		{
			e.printStackTrace();
			showErrorMessage("Unable to determine local hostname");
		}*/
		catch (WindeyClientDataProviderException e)
		{
			e.printStackTrace();
			showErrorMessage("Error capturing screen");
		} 
		/*catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			showErrorMessage("Unknown host") ;
		}*/
	}

	private void disconnect()
	{
		try
		{
			if (connection.isConnected())
			{				
				connection.disconnect();
				JOptionPane.showMessageDialog(null, "You are disconnected from the server") ;
			}
		}
		catch (WindeyServerConnectionException e)
		{
			e.printStackTrace();
			showErrorMessage("Unable to disconnect");
		}
	}
	
	private void showErrorMessage(String message)
	{
		
		JOptionPane.showMessageDialog(null, message, "Windey Client Error", JOptionPane.ERROR_MESSAGE);
	}

	/**
	 * @return of we data ontvangen of niet
	 */
	public boolean isReceiving()
	{
		return this.receiving;
	}

	/**
	 * @return of we aan het streamen zijn of niet
	 */
	public boolean isStreaming()
	{
		return this.streaming;
	}

	/**
	 * @param receive stel de receivestatus in
	 */
	public void setReceiving(boolean receive)
	{
		this.receiving = receive;
	}

	/**
	 * @param stream stel de steamstatus in
	 */
	public void setStreaming(boolean stream)
	{
		this.streaming = stream;
	}
}
